package com.amos.mqserver.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * @author amos on 2018/9/13 0013.
 */
@Configuration
public class DataSourceConfig {

    @Value("${druid.jdbc.driveClassName:com.mysql.jdbc.Driver}")
    String driveClassName;

    @Value("${druid.jdbc.jdbcUrl:jdbc:mysql://10.3.98.153:3306/tpdb?useSSL=true}")
    String jdbcUrl;

    @Value("${druid.jdbc.jdbcUsername:rxbiz}")
    String jdbcUsername;

    @Value("${druid.jdbc.jdbcPassword:rxHuntkey!123A}")
    String jdbcPassword;

    @Value("${druid.jdbc.maxActive:20}")
    Integer maxActive;

    @Value("${druid.jdbc.initialSize:2}")
    Integer initialSize;

    @Value("${druid.jdbc.maxWait:60000}")
    Integer maxWait;

    @Value("${druid.jdbc.minIdle:0}")
    Integer minIdle;

    @Value("${druid.jdbc.validationQuery:SELECT 1}")
    String validationQuery;

    @Value("${druid.jdbc.testWhileIdle:false}")
    Boolean testWhileIdle;

    @Value("${druid.jdbc.testOnBrowwon:true}")
    Boolean testOnBrowwon;

    @Value("${druid.jdbc.poolPreparedStatements:false}")
    Boolean poolPreparedStatements;

    @Bean(name = "mqDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driveClassName);
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        dataSource.setMaxActive(maxActive);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxWait(maxWait);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(testOnBrowwon);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        return dataSource;
    }

    @Bean(name = "mqJdbcTemplate")
    public JdbcTemplate primaryTemplate(@Qualifier("mqDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
